<template>
  <div class="search-input" >
    <div class="search">
      <el-input 
        placeholder="患者/电话/病历号" 
        class="title-input-radius" 
        v-model="person" 
        @input="queryCustomer"
        @blur="onBlur"
        @focus="queryCustomer"
        clearable
        >
        <template #prefix>
          <el-icon style="font-size: 20px; color: #000; padding-top: 5px;"><search  /></el-icon>
        </template>
      </el-input>
    </div>
    <div class="search-info" v-show="isSearchValue">
      <div class="info-head">
        <span>找到{{personListLength}}个患者</span>
        <div>
            <el-checkbox v-model="isChecked" label="按就诊时间排序"></el-checkbox>
          </div>
      </div>
      <div class="info-main">
        <ul>
          <li class="person-item" v-for="i in personList" :key="i.id" >
            <searchItem @searchItem="handleItem" @goRegister="goRegister" :searchData="i"></searchItem>
          </li>
          
        </ul>
      </div>
      <!-- <div class="info-footer">
        <span>创建新患者</span>
      </div> -->
    </div>
  </div>
  

  <!-- 新增/挂号/ 预约/  -->
  <el-drawer
			size="45%"
			:title="title"
			v-model="showDrawer"
			:before-close="drawerClose" destroy-on-close>
			<zaddpatient 
					@cancel="cancel" 
					@saveMakeAnAppointment="saveMakeAnAppointment" 
					@saveAndRegister="saveAndRegister"
					v-if="isADD === 'add'"
					></zaddpatient>
			
			<zregister v-if="isADD === 'register'"
				@cancel="cancel" 
				@handlebtn="handlebtn"
        :userId="userId"
				></zregister>

			<zmakeanapp v-if="isADD === 'makeanapp'"
				@handlebtn="handlebtn"
				@cancel="cancel"

				></zmakeanapp>
    </el-drawer>

</template>

<script lang="ts">
import { Search } from '@element-plus/icons-vue'
import { defineComponent, ref, watch, onUnmounted, onMounted } from '@vue/runtime-core'
import useRequet, { RespData } from "../../hook/network"
import { useRouter } from "vue-router"
import { ElMessage, ElMessageBox } from 'element-plus'

// 详情添加患者
import useSetAddLog from "../../hook/setAddLog"

import zmakeanapp from "../../components/patient/makeAnAppointment.vue"
import zaddpatient from "../../components/patient/add.vue"
import zregister from "../../components/patient/register.vue"


import searchItem, { SearchItemType } from "./searchItem.vue"

// 防抖
import { debounce } from "../../utils/debounce"



export default defineComponent ({
  name: 'searchInput',
  components: {
    zmakeanapp,
    zaddpatient,
    zregister,

    searchItem,
    Search
  },
  setup() {
    const request = useRequet({ path: "" });
    const router = useRouter()
    const isSearchValue = ref(false)
    const person = ref('')
    const personListLength = ref(0)
    const personList = ref([] as any[])
    const isChecked = ref(true)
    const userId = ref()
    watch(() => personList.value, (newList, prevList) => {
      personListLength.value = newList.length || 0
    })

    watch(() => isChecked.value, (newV) => {
      if(newV) {
        getPersonList()
      }
    })
    
    // 得到数据
    const getPersonList = () => {
      if(!person.value) {
        isSearchValue.value = false
        return false
      }
      request.sendRequest({
        address: `customer/info/queryCustomer/`,
        params: {
          queryValue: person.value,
          orderByLastRecord: isChecked.value
        },
        success: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error('获取患者' + resp.msg)
          personList.value = resp.data.records || []
        },
        fail: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg)
          
        },
        method: "POST",
      })
    }
    let timer:any = null
    const debounceSearch = debounce(getPersonList, 200)
    const queryCustomer = () => {
      clearTimeout(timer)
      timer = setTimeout(() => {
        if(person.value) {
          isSearchValue.value = true
        }
      }, 200)

      console.log(timer, 'timer')
      debounceSearch()
      
    }
    const handleItem = (data: SearchItemType) => {
      let id = data.id
      isSearchValue.value = false
      useSetAddLog(id)
      router.push(`/allPatientDetails/${id}/patient`)
    }
    
    const onBlur = () => {
      clearTimeout(timer)
      timer = setTimeout(() => {
        isSearchValue.value = false
      },200)
    }

    onUnmounted(() => {
      clearTimeout(timer)
      timer = null
    })

    const goRegister = (data: any) => {
      userId.value = data.id
      isSearchValue.value = false
      showDrawer.value = true
      isADD.value = 'register'
			title.value = "挂号"
    }

    const registerInfo = ref({} as any)

    // 抽屉 --》 新建预约部分
    const showDrawer = ref(false)
    const title = ref('')
    const isADD = ref('')
    // 打开新建预约
    const saveMakeAnAppointment = () => {
      isADD.value = 'makeanapp'
			title.value = "新建预约"
    }

    const saveAndRegister = () => {
			isADD.value = 'register'
			title.value = "挂号"
		}


    const handlebtn = () => {
      isADD.value = 'add'
			title.value = "个人信息"
    }
    const drawerClose = () => {
      ElMessageBox.confirm('此操作将关闭窗口, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
				showDrawer.value = false
			}).catch(() => {
					ElMessage({
						type: 'info',
						message: '已取消',
					});
      })
    }
    const cancel = () => {
      showDrawer.value = false
    }
    return {
      person,
      isSearchValue,
      personList,
      personListLength,
      queryCustomer,
      handleItem,
      onBlur,
      userId,
      isChecked,

      goRegister,

      showDrawer,
      title,
      isADD,
      saveMakeAnAppointment,
      saveAndRegister,
      handlebtn,
      drawerClose,
      cancel,
      registerInfo,
    }
  }
})
</script>

<style lang="scss" scoped>
  .search-input {
    position: relative;

    .search-info {
      position: absolute;
      top: 50px;
      z-index: 99;
      min-width: 380px;
      background-color: white;
      border-radius: 4px;
      box-shadow: 0px 2px 8px #e9e9e9;
      display: flex;
      flex-direction: column;
      font-size: 13px;
      color: $primaryText;
      max-height: 330px;
      

      .info-head {
        height: 30px;
        line-height: 30px;
        color: $regularText;
        padding-left: 10px;
        border-bottom: 1px solid #e9e9e9;
        display: flex;

        & > div {
          flex: 1;
          text-align: right;
          margin-right: 10px;
        }
      }

      .info-main {
        flex: 1;
        overflow-y: auto;

        ul, li {
          list-style: none;
          padding: 0;
          margin: 0;
        }

        .person-item {
          max-height: 80px;
          
          
        }
      }

      .info-footer {
        height: 40px;
        line-height: 40px;
        color: $mainColor;
        border-top: 1px solid #e9e9e9;
        padding-left: 10px;
      }
    }
  }
  
</style>